//
//  ZillaClient.m
//  chameleon
//
//  Created by Justin Yip on 6/19/14.
//
//

#import "ZillaClient.h"
#import <AFNetworking.h>

//变色龙更新key
NSString* const kAppKey = @"282d245c3d5b069a1f797cc2b4aaa50b";
//应用密钥
NSString* const kSecret = @"cd5c43d8-694c-4f5c-b63b-b290cb6ac217";
//变色龙服务器地址
NSString* const kServerUrl = @"http://115.28.1.119:18860";

@implementation ZillaClient

//应用验证
-(RACSignal*)authenticateApplication
{
    
}

+(NSString*)URLStringForFile:(NSString*)identifier
{
    return [NSString stringWithFormat:@"%@/bsl-web/mam/attachment/download/%@", kServerUrl, identifier];
//    NSString *url = [NSString stringWithFormat:@"%@/mam/api/mam/clients/files/%@?appKey=%@", kServerUrl, identifier, kAppKey];
//    return url;
}

+(RACSignal*)getLastestAppVersion
{
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        
        //应用ID
        NSString *identifier = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIdentifier"];
        
        //更新接口地址
        NSString *updateURL =[NSString stringWithFormat:@"%@/mam/api/mam/clients/update/ios/%@?appKey=%@&ts=%f",
                              kServerUrl,
                              identifier,
                              kAppKey,
                              [NSDate timeIntervalSinceReferenceDate]];
        
        //request
        NSMutableURLRequest *mutableRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:updateURL]
                                                                      cachePolicy:NSURLCacheStorageNotAllowed
                                                                  timeoutInterval: 10];
        [mutableRequest setHTTPMethod:@"GET"];
        [mutableRequest setValue:@"application/json; charset = utf-8" forHTTPHeaderField:@"Content-Type"];
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        AFHTTPRequestOperation *op = [manager HTTPRequestOperationWithRequest:mutableRequest success:^(AFHTTPRequestOperation *operation, id responseObject) {
            if (!responseObject) {
                [subscriber sendError:[NSError errorWithDomain:@"chameleon" code:0 userInfo:@{@"errmessage": @"解析错误"}]];
            } else {
                [subscriber sendNext:responseObject];
            }
            
            [subscriber sendCompleted];
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            
            [subscriber sendError:error];
        }];//op
        
        [manager.operationQueue addOperation:op];
        [op start];
        
        return [RACDisposable disposableWithBlock:^{
            [op cancel];
        }];//return disposable
        
    }];
}

+(NSString*)itmsURLStringForAppPlistFileID:(NSString *)package
{
    NSString *downloadURL = [self URLStringForFile:package];
//    NSString *updateURL =[NSString stringWithFormat:@"%@/bsl-web/mam/attachment/download/%@", kServerUrl, package];
    NSString *itmsURL = [NSString stringWithFormat:@"itms-services://?action=download-manifest&url=%@", downloadURL];
    return itmsURL;
}

+ (NSString *)validateApplication {
    
    //应用ID
    NSString *identifier = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"CFBundleIdentifier"];
    //应用版本号
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    NSString *version = [infoDictionary objectForKey:@"CFBundleVersion"];
    
    NSString* validateUrl = [NSString stringWithFormat:@"%@/mam/api/mam/clients/apps/%@/%@/%@/validate",kServerUrl,@"ios",identifier,version];
    
    NSDictionary* postBody = [[NSDictionary alloc] initWithObjectsAndKeys:kAppKey, @"appKey", kSecret, @"secret", nil];
    
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager POST:validateUrl parameters:postBody success:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSDictionary* response = responseObject;
        NSString* token = [response objectForKey:@"token"];
        NSString* expired = [response objectForKey:@"expired"];
        
        NSLog(@"token: %@,expired: %@", token,expired);
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"Error: %@", error);
    }];
    
    return NULL;
}

+ (void)checkInWithToken:(NSString *)token done:(void (^)(id))done {
    

    NSString* checkInUrl = [NSString stringWithFormat:@"%@/push/api/checkinservice/checkins",kServerUrl];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    NSString *adId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    
    NSDictionary* putParams = @{
                                @"deviceId": adId,
                                @"appId": kAppKey,
                                @"pushToken": token,
                                @"channelId": @"apns",
                                @"deviceName": @"iPhone4S",
                                @"osName": @"ios",
                                @"osVersion": [[UIDevice currentDevice] systemVersion]
                                };
//    manager.requestSerializer = [AFJSONRequestSerializer serializer];
//    [manager.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//    manager.responseSerializer = [AFJSONResponseSerializer serializer];
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/x-json"];
//    
//    [manager PUT:checkInUrl parameters:putParams success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        
//        NSLog(@"%@",responseObject);
//
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        NSLog(@"%@",error);
//    }];
    
//    NSString* success = adId;
//    done(success);
//    
//    manager.requestSerializer = [AFJSONRequestSerializer serializer];
//    manager.responseSerializer = [AFJSONResponseSerializer serializer];
//    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/x-json"];
//    
//    NSMutableURLRequest* request = [[AFJSONRequestSerializer serializer] requestWithMethod:@"PUT" URLString:@"http://www.baidu.com" parameters:putParams error:nil];
//    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
//    AFHTTPRequestOperation* op = [manager HTTPRequestOperationWithRequest:request success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        NSLog(@"%@",responseObject);
//    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
//        NSLog(@"%@",error);
//    }];
//    
//    [manager.operationQueue addOperation:op];
//    [op start];
    
    NSURL* url = [[NSURL alloc] initWithString:checkInUrl];
    NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:url];
    NSData* jsonData = [NSJSONSerialization dataWithJSONObject:putParams options:NSJSONWritingPrettyPrinted error:Nil];
    NSString* jsonStr = [[NSString alloc] initWithData:jsonData encoding:NSASCIIStringEncoding];
//    NSString* putData = [[NSString alloc] initWithFormat:@"message%@",jsonStr];
    NSData* sendData = [jsonStr dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString* postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[jsonStr length]];
    [request setHTTPMethod:@"PUT"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    [request setHTTPBody:sendData];
    NSHTTPURLResponse* urlResponse = nil;
    NSError *error = [[NSError alloc] init];
    NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&error];
    NSString* resStr = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    NSLog(@"%@",resStr);
}
@end
